//
//  UploadViewController.m
//
//
//  Created by jing zhao on 4/28/16.
//  Copyright © 2016 jing zhao. All rights reserved.
//

#import "UploadViewController.h"
#import "UpLoadCollectionViewCell.h"
#import "NetApI.h"
#import "PickerHeader.h"
#import <Photos/Photos.h>
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "SelectTableView.h"
#import "UploadActivityView.h"
#import "UploadAddCollectionViewCell.h"
#import "UIColor+LocalColor.h"

#define marginWidth 8.0

@interface UploadViewController () <UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UIActionSheetDelegate,
DelegateSelectTableView,
ProtocalTapCancel,
UITextViewDelegate>

@property ( assign , nonatomic ) IBOutlet UICollectionView     *collectionView;
@property ( weak   , nonatomic ) IBOutlet UITextView           *markTextView;
@property ( weak   , nonatomic ) IBOutlet UILabel              *labelUpload;
@property (weak, nonatomic) IBOutlet UIView                    *headerView;
@property (weak, nonatomic) IBOutlet UIScrollView              *scrollView;


@property ( assign , nonatomic ) IBOutlet NSLayoutConstraint   *uploadHeight;
@property ( assign , nonatomic ) IBOutlet NSLayoutConstraint   *uploadConstant;
@property ( strong , nonatomic ) UIAlertController             *actionSheet;
@property ( assign , nonatomic ) PHAssetMediaType   mediaTypeSlect;
@property ( strong , nonatomic ) SelectTableView    *tableViewSelectUpload;
@property ( weak   , nonatomic ) IBOutlet UIView    *contentContainView;

@property ( strong , nonatomic ) NSMutableArray *arrayData;
@property ( strong , nonatomic ) NSMutableArray *arrayImage;
@property ( strong , nonatomic ) NSMutableArray *arrayResultData;
@property ( strong , nonatomic ) NSMutableArray *arrayCompressedResultData;
@property ( strong , nonatomic ) NSMutableArray *arrayVideoCompressedAv;
@property ( strong , nonatomic ) NSMutableArray *arrayNetTaskUpload;

@property ( assign , nonatomic ) CGFloat  floatDataSize;
@property ( assign , nonatomic ) CGFloat  floatDataCompressedSize;

@property ( strong , nonatomic ) NSString * activityId;
@property ( strong , nonatomic ) NSString * userId;
@property ( assign , nonatomic ) NSInteger numberAllCount;
@property ( assign , nonatomic ) NSInteger numberLoadCount;

@property ( strong , nonatomic ) UploadActivityView *upLoadActivity;

@end

@implementation UploadViewController

-(void)setDataArray:(NSMutableArray*)array{
    
    _arrayData = [NSMutableArray arrayWithArray:array];
    PHAsset *asset = _arrayData[0][@"PHAsset"];
    _mediaTypeSlect = asset.mediaType;
    if (_mediaTypeSlect == PHAssetMediaTypeVideo) {
        _arrayVideoCompressedAv = [NSMutableArray array];
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _arrayImage = [NSMutableArray arrayWithArray:[self loadImageWithArray:array]];
        [self.collectionView reloadData];
    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.floatDataSize = 0.0;
    self.floatDataCompressedSize = 0.0;
    _arrayResultData = [NSMutableArray array];
    _arrayCompressedResultData= [NSMutableArray array];
    _arrayNetTaskUpload = [NSMutableArray array];
    self.activityId = @"";
    self.userId = [[NSUserDefaults standardUserDefaults]objectForKey:UPLOADUSERID];
    self.markTextView.layer.borderColor = [[UIColor getLineGrayColor]CGColor];
    self.markTextView.layer.borderWidth = 1.0;
    self.markTextView.delegate = self;
    self.labelUpload.layer.borderColor = [[UIColor getLineGrayColor]CGColor];
    self.labelUpload.layer.borderWidth = 1.0;
    
    [self.collectionView registerNib:[UINib nibWithNibName:UpLoadCollectionViewCellName bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:IndentifyUpLoadCollectionViewCell];
    [self.collectionView registerNib:[UINib nibWithNibName:UpLoadAddCollectionViewCellName bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:IndentifyAddUpLoadCollectionViewCell];
    
    //collectionViewHeight
    float InterSpace = 8.0;
    UICollectionViewFlowLayout *collectionFlow = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    collectionFlow.minimumLineSpacing = InterSpace;
    collectionFlow.minimumInteritemSpacing = InterSpace;
    float width = ([UIScreen mainScreen].bounds.size.width-20.0*2-InterSpace*4)/3.0;
    collectionFlow.itemSize = CGSizeMake(width, width);
    int heightCount = 0 ;
    if ([self.arrayData count] == 9)
        heightCount = 3;
    else
        heightCount  = (ceilf(([self.arrayData count]+1)/3.0) >3) ? 3 : ceilf(([self.arrayData count]+1)/3.0);
    float floatCollectionHight = width*heightCount+marginWidth*heightCount+marginWidth;
    self.uploadHeight.constant = floatCollectionHight;
    float floatHeight =[UIScreen mainScreen].bounds.size.height-38-20*2-floatCollectionHight;
    if (self.uploadConstant.constant <floatHeight)self.uploadConstant.constant = floatHeight;
    
    [self initTableView];
    [self loadUploadType];
}


#pragma mark LoadImage

-(NSArray *) loadImageWithArray:(NSArray*)arrayData {
    NSMutableArray *arrayImageLoad = [NSMutableArray arrayWithCapacity:[arrayData count]];
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    //同步
    options.synchronous = YES;
    for (int i = 0;i<[arrayData count];i++) {
        PHAsset *asset = arrayData[i][@"PHAsset"];
        [[PHImageManager defaultManager]requestImageForAsset:asset
                                                  targetSize:CGSizeMake(100, 100)
                                                 contentMode:PHImageContentModeAspectFill
                                                     options:options
                                               resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                   [arrayImageLoad addObject:result];
                                               }];
    }
    return arrayImageLoad;
}

#pragma mark private

-(void) initTableView {
    _tableViewSelectUpload = [[[NSBundle mainBundle]loadNibNamed:@"SelectTableView" owner:self options:nil] firstObject];
    self.tableViewSelectUpload.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableViewSelectUpload.tableView.backgroundColor = [UIColor whiteColor];
    self.tableViewSelectUpload.layer.borderWidth = 1.0;
    self.tableViewSelectUpload.layer.borderColor = [[UIColor getLineGrayColor]CGColor];
    [self.contentContainView addSubview:self.tableViewSelectUpload];
    self.tableViewSelectUpload.hidden = YES;
    
}

-(void) addTableViewConstraitsWithArray:(NSArray *)arrayData {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableViewSelectUpload configureData:arrayData andDelegateSelect:self];
        [self.contentContainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(10.0)-[_tableViewSelectUpload]-(10.0)-|"
                                                                                        options:0
                                                                                        metrics:nil
                                                                                          views:NSDictionaryOfVariableBindings(_tableViewSelectUpload)]];
        float height = [arrayData count] > 3 ? 3*40 :[arrayData count]*40;
        [self.contentContainView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_labelUpload][_tableViewSelectUpload(==height)]"
                                                                                        options:0
                                                                                        metrics:@{@"height":[NSNumber numberWithFloat:height]}
                                                                                          views:NSDictionaryOfVariableBindings(_labelUpload,_tableViewSelectUpload)]];
        
    });
}

-(void)loadAddSuccess {
    self.numberLoadCount = self.numberLoadCount + 1;
    if(self.numberLoadCount == self.numberAllCount){
        [self.upLoadActivity removeFromSuperview];
        NSLog(@"上传成功");
        [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATIONUPLOADSUCESS object:nil];
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            
        }];
        
    }else{
        self.upLoadActivity.uploadNum.text = [NSString stringWithFormat:@"%d/%ld",self.numberLoadCount+1,(long)self.numberAllCount];
    }
    
}

-(void)loadFailure {
    [self delegateCancel];
    [SVProgressHUD showErrorWithStatus:@"上传失败"];
    NSLog(@"上传失败");
}


-(void)addUploadView{
    _upLoadActivity = [[[NSBundle mainBundle]loadNibNamed:@"UploadActivityView" owner:self options:nil]firstObject];
    self.upLoadActivity.delegateTapCancel = self ;
    self.upLoadActivity.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.upLoadActivity];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_upLoadActivity]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_upLoadActivity)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_headerView][_upLoadActivity]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_headerView,_upLoadActivity)]];
}

#pragma mark ProtocalTapCancel

-(void)delegateCancel{
    [self.upLoadActivity.activity stopAnimating];
    [self.upLoadActivity removeFromSuperview];
    for (NSURLSessionDataTask *dataTask in _arrayNetTaskUpload) {
        [dataTask cancel];
    }
}

#pragma mark video

-(CGFloat) getSizeVideoWithArrayData:(NSArray *)arrayData {
    CGFloat videoSize = 0;
    for (int i = 0;i<[arrayData count];i++) {
        PHAsset *asset = arrayData[i][@"PHAsset"];
        //在异步里用信号机制做同步
        dispatch_semaphore_t    semaphore = dispatch_semaphore_create(0);
        PHVideoRequestOptions *option = [PHVideoRequestOptions new];
        option.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
        __block NSData *assetData = nil;
        
        [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:option resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
            AVURLAsset *resultAsset =(AVURLAsset*) avasset;
            [_arrayVideoCompressedAv addObject:avasset];
            assetData  = [NSData dataWithContentsOfURL:resultAsset.URL];
            dispatch_semaphore_signal(semaphore);
        }];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self.arrayResultData addObject:assetData];
        videoSize = +assetData.length/1024.0;
    }
    return videoSize;
}

-(CGFloat) getCompressedSizeVideoWithArrayData:(NSArray *)arrayData {
    CGFloat videoSize = 0;
    for (AVAsset *avAsset in self.arrayVideoCompressedAv) {
        //在异步里用信号机制做同步
        dispatch_semaphore_t    semaphore = dispatch_semaphore_create(0);
        
        __block NSData *assetData = nil;
        
        NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
        NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:@"temp.mov"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
            [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
        
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetLowQuality];
        exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        exportSession.shouldOptimizeForNetworkUse = YES;
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void){
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCompleted:
                    assetData = [NSData dataWithContentsOfURL:exportSession.outputURL];
                    dispatch_semaphore_signal(semaphore);
                    NSLog(@"AVAssetExportSessionStatusCompleted");
                    break;
                    
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"AVAssetExportSessionStatusFailed");
                    break;
                default:
                    break;
            }
        }];
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        if (assetData) {
            [self.arrayCompressedResultData addObject:assetData];
            videoSize = +assetData.length/1024.0;
        }else
            return 0;
    }
    return videoSize;
}

#pragma mark image size

-(CGFloat) getSizeWithArrayImage:(NSMutableArray*)imageArray {
    CGFloat allSize = 0.0;
    for ( UIImage *image in imageArray ) {
        NSData *data;
        if (UIImagePNGRepresentation(image) !=nil) {
            data = UIImagePNGRepresentation(image);
        }else{
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        if (data != nil) {
            [self.arrayResultData addObject:data];
            allSize = + data.length/1024.0;
        }else
            NSLog(@"getSize image has no CGImageRef or invalid bitmap format  传递出错请检查错误");
        
    }
    return allSize;
}

-(CGFloat) getCompressedWithArrayImage:(NSMutableArray*)imageArray {
    CGFloat compressedSize = 0.0;
    for ( UIImage *image in imageArray ) {
        NSData *data;
        if (UIImageJPEGRepresentation(image, 1.0) !=nil) {
            data = UIImageJPEGRepresentation(image, 0.5);
        }else{
            data = UIImagePNGRepresentation(image);
        }
        
        if (data != nil) {
            [self.arrayCompressedResultData addObject:data];
            compressedSize = + data.length/1024.0;
        }else
            NSLog(@"getCompressed image has no CGImageRef or invalid bitmap format 传递出错请检查错误");
    }
    return compressedSize;
}

#pragma mark image upload

-(void) loadUploadType{
    [SVProgressHUD show];
    [NetApI postApiNetWithApi:[NSString stringWithFormat:@"http://120.24.55.7:9191/staff/%@",@"activity/getActivityList"]
                    andParams:@{@"userId":self.userId} andSucces:^(NSObject *object) {
                        NSDictionary *responseData = (NSDictionary*)object;
                        int number = [responseData[@"code"]intValue];
                        if (number  == 0) {
                            [SVProgressHUD dismiss];
                            NSArray *arrayActivityList = responseData[@"data"][@"activityList"];
                            [self addTableViewConstraitsWithArray:arrayActivityList];
                        }
                    } andFailure:^(NSObject *object) {
                        [SVProgressHUD showSuccessWithStatus:@"请求类型失败"];
                        NSLog(@"请求类型失败");
                    }];
}

-(void) uploadDataWithDataArray:(NSArray*)arrayData {
    
    self.numberAllCount = [arrayData count];
    self.numberLoadCount = 0;
    if ([self.activityId isEqualToString:@""]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"消息" message:@"请选择Upload to" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    if ([self.arrayData count] == 0) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"消息" message:@"请选择资源文件" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    [self addUploadView];
    [self.upLoadActivity.activity startAnimating];
    self.upLoadActivity.uploadNum.text = [NSString stringWithFormat:@"1/%lu",(unsigned long)self.numberAllCount];
    
    NSDate *dateNow = [NSDate date];
    NSString *timeStamp = [NSString stringWithFormat:@"%ld", (long)[dateNow timeIntervalSince1970]];
    for (NSData *data in arrayData) {
        NSInteger intData = [arrayData indexOfObject:data];
        NSURLSessionDataTask *sessionDataTask;
        if (self.mediaTypeSlect == PHAssetMediaTypeImage ) {
            NSDictionary *parameters = @{@"fileNo":[NSString stringWithFormat:@"0%ld",(long)intData+1],
                                         @"actiontype":@"1",
                                         @"activityId":self.activityId,
                                         @"type":@"activity",
                                         @"remark":self.markTextView.text,
                                         @"batch_flag":timeStamp,
                                         @"userId":self.userId
                                         };
            
            sessionDataTask = [[AFHTTPSessionManager manager]POST:[NSString stringWithFormat:@"http://120.24.55.7:9191/staff/%@",@"activity/saveUploadPicOrVideoSingle"] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                [formData appendPartWithFileData:data name:@"file" fileName:@"file" mimeType:@"image/jpg"];
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
                [self loadAddSuccess];
            }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self loadFailure];
            }];
            
        } else {
            NSDictionary *parameters = @{@"fileNo":[NSString stringWithFormat:@"0%ld",(long)intData+1],
                                         @"actiontype":@"3",
                                         @"activityId":self.activityId,
                                         @"type":@"activity",
                                         @"remark":self.markTextView.text,
                                         @"batch_flag":timeStamp,
                                         @"userId":self.userId
                                         };
            sessionDataTask = [[AFHTTPSessionManager manager]POST:[NSString stringWithFormat:@"http://120.24.55.7:9191/staff/%@",@"activity/saveUploadPicOrVideoSingle"] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                [formData appendPartWithFileData:data name:@"file" fileName:@"myVideo.mov" mimeType:@"video/quicktime"];
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
                [self loadAddSuccess];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self loadFailure];
            }];
        }
        [self.arrayNetTaskUpload addObject:sessionDataTask];
    }
}

#pragma  mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([self.arrayImage count] == 9)
        return 9 ;
    return [self.arrayImage count]+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *collectionCell;
    if (indexPath.row == [self.arrayImage count]+1-1) {
        UploadAddCollectionViewCell *collectionAddCell = [collectionView dequeueReusableCellWithReuseIdentifier:IndentifyAddUpLoadCollectionViewCell forIndexPath:indexPath];
        collectionCell = collectionAddCell;
    }else{
        UpLoadCollectionViewCell *collectionCellTemp = [collectionView dequeueReusableCellWithReuseIdentifier:IndentifyUpLoadCollectionViewCell forIndexPath:indexPath];
        UIImage *imageTemp = [self.arrayImage objectAtIndex:indexPath.row];
        [collectionCellTemp configureImage:imageTemp];
        collectionCell = collectionCellTemp;
    }
    return collectionCell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(8.0, 8.0, 8.0, 8.0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.arrayImage count] == 9)
        return;
    if (indexPath.row == [self.arrayImage count]+1-1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -DelegateSelectTableView

-(void)delegateSelect:(NSDictionary*)dic{
    self.labelUpload.text = [NSString stringWithFormat:@"  %@",dic[@"subject"]];
    self.activityId = dic[@"id"];
    self.tableViewSelectUpload.hidden = YES;
}

#pragma mark -tap

- (IBAction)select:(id)sender {
    if (self.tableViewSelectUpload) {
        self.tableViewSelectUpload.hidden = !self.tableViewSelectUpload.hidden;
    }
}

- (IBAction)back:(id)sender {
    [SVProgressHUD dismiss];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)upLoad:(id)sender {
    if (self.floatDataSize < 0.1) {
        if (self.mediaTypeSlect == PHAssetMediaTypeImage) {
            self.floatDataSize = [self getSizeWithArrayImage:self.arrayImage];
            self.floatDataCompressedSize = [self getCompressedWithArrayImage:self.arrayImage];
        } else if (self.mediaTypeSlect == PHAssetMediaTypeVideo) {
            self.floatDataSize = [self getSizeVideoWithArrayData:self.arrayData];
            self.floatDataCompressedSize = [self getCompressedSizeVideoWithArrayData:self.arrayData];
        }
    }
    if (!self.actionSheet) {
        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *alertActionNormal = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@%1.1f Kb)",@"Medium(",self.floatDataCompressedSize] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self uploadDataWithDataArray:self.arrayCompressedResultData];
        }];
        UIAlertAction *alertActionCompressed = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"%@%1.1f Kb)",@"Large(",self.floatDataSize] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self uploadDataWithDataArray:self.arrayResultData];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [actionSheet addAction:alertActionNormal];
        [actionSheet addAction:alertActionCompressed];
        [actionSheet addAction:cancelAction];
        self.actionSheet = actionSheet;
    }
    [self presentViewController:self.actionSheet animated:YES completion:nil];
}

#pragma mark -textView

- (void)textViewDidBeginEditing:(UITextView *)textView {
    self.scrollView.contentOffset = CGPointMake(0, 200.0);
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    self.scrollView.contentOffset = CGPointMake(0, 0);
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

@end
